package cn.edu.xjtu.nbrash.xbarsuite.terry;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;
import cn.edu.xjtu.nbrash.xbarsuite.R;
import cn.edu.xjtu.nbrash.xbarsuite.utilities.WifiManage;
import cn.edu.xjtu.nbrash.xbarsuite.zxingdemo.RashDisplayActivity;

import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.wifi.WifiConfigInfo;

public class EncodeWifiConfig extends Activity implements OnClickListener,
		OnItemSelectedListener {

	private Button mBtnGenerate;
	private Button mBtnBack;
	private Button mBtnReadConfig;
	private EditText mSSID, mUserName, mPasswd;
	private Spinner spinner;
	private String[] cypherMethods = new String[] { "NO_PASSWORD", "WEP",
			"WPA", "EAP" };
	private int choice = 0;

	private PopupWindow popupWindow;
	private LinearLayout layout;
	private ListView listView;
	private List<WifiConfigInfo> wifiConfigInfos = new ArrayList<>();

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_encode_wifi);
		initView();

	}

	public void initView() {
		mBtnGenerate = (Button) findViewById(R.id.generate_btn);
		mBtnBack = (Button) findViewById(R.id.back_btn);
		mBtnReadConfig = (Button) findViewById(R.id.readconfig_btn);
		mBtnGenerate.setOnClickListener(this);
		mBtnBack.setOnClickListener(this);
		mBtnReadConfig.setOnClickListener(this);

		mSSID = (EditText) findViewById(R.id.wifi_ssid);
		mUserName = (EditText) findViewById(R.id.wifi_name);
		mPasswd = (EditText) findViewById(R.id.wifi_password);

		spinner = (Spinner) this.findViewById(R.id.spinner_cyphermethods);
		// ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
		// android.R.layout.simple_dropdown_item_1line, cypherMethods);
		// spinner.setAdapter(aa);
		// 设置下拉方式
		// aa.setDropDownViewResource(android.R.layout.simple_spinner_item);
		// MyOnItemSelectedListener ml = new MyOnItemSelectedListener();
		spinner.setOnItemSelectedListener(this);

	}

	@Override
	public void onBackPressed() {// 捕获返回键
		finish();
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.generate_btn:
				estimate();
				break;
			case R.id.back_btn:
				finish();
				// readConfig();
				break;
			case R.id.readconfig_btn:
				readConfig();
				break;
			default:
				break;
		}
	}

	private void readConfig() {
		String[] listNames;
		try {
			wifiConfigInfos = WifiManage.Read();

		} catch (Exception e) {
			Toast.makeText(this.getBaseContext(), "请查看是否有root权限",
					Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		listNames = new String[wifiConfigInfos.size()];
		int i = 0;
		Iterator<WifiConfigInfo> iw = wifiConfigInfos.iterator();
		while (iw.hasNext()) {
			WifiConfigInfo wifiInfo = iw.next();
			listNames[i++] = wifiInfo.getSsid();
		}
		Rect frame = new Rect();
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		int state_heght = frame.top;// 状态栏的高度

		int y = mBtnReadConfig.getBottom() + state_heght;
		int x = getWindowManager().getDefaultDisplay().getWidth() / 4;

		showPopupWindow(x, y, listNames);

	}

	public void showPopupWindow(int x, int y, String[] listNames) {
		layout = (LinearLayout) LayoutInflater.from(EncodeWifiConfig.this)
				.inflate(R.layout.wifi_dialog, null);
		listView = (ListView) layout.findViewById(R.id.lv_dialog);
		listView.setAdapter(new ArrayAdapter<String>(EncodeWifiConfig.this,
				R.layout.wifi_text, R.id.tv_text, listNames));

		popupWindow = new PopupWindow(EncodeWifiConfig.this);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow
				.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 2);
		popupWindow.setHeight(600);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setContentView(layout);
		// showAsDropDown会把里面的view作为参照物，所以要那满屏幕parent
		// popupWindow.showAsDropDown(findViewById(R.id.tv_title), x, 10);
		popupWindow.showAtLocation(findViewById(R.id.wifi_main), Gravity.LEFT
				| Gravity.TOP, x, y);// 需要指定Gravity，默认情况是center.

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// mBtnReadConfig.setText(title[arg2]);
				WifiConfigInfo info = wifiConfigInfos.get(arg2);
				spinner.setSelection(0, true);
				mSSID.setText("");
				mUserName.setText("");
				mPasswd.setText("");
				switch (info.getType()) {
					case NO_PASSWORD:
						spinner.setSelection(0, true);
						mSSID.setText(info.getSsid());
						break;
					case WEP:
						spinner.setSelection(1, true);
						mSSID.setText(info.getSsid());
						mPasswd.setText(info.getPreSharedKey());
						break;
					case WPA:
						spinner.setSelection(2, true);
						mSSID.setText(info.getSsid());
						mPasswd.setText(info.getPreSharedKey());
						break;
					case EAP:
						spinner.setSelection(3, true);
						mSSID.setText(info.getSsid());
						mUserName.setText(info.getIdentity());
						mPasswd.setText(info.getPasswd());
						break;
					default:
						break;
				}
				popupWindow.dismiss();
			}
		});
	}

	private void estimate() {
		String ssid = mSSID.getText().toString();
		String name = mUserName.getText().toString();
		String passwd = mPasswd.getText().toString();
		StringBuilder sb = new StringBuilder();
		String text = "";
		switch (choice) {
		// 没有密码
			case 0:
				if (ssid.equals("")) {
					Toast.makeText(this.getBaseContext(), "请填写完整信息",
							Toast.LENGTH_SHORT).show();
				} else {
					sb.append("WIFI:T:").append(cypherMethods[choice])
							.append(";S:").append(ssid).append(";");
				}
				break;
			case 3:
				if (ssid.equals("") || name.equals("") || passwd.equals("")) {
					Toast.makeText(this.getBaseContext(), "请填写完整信息",
							Toast.LENGTH_SHORT).show();
				} else {
					// 生成
					sb.append("WIFI:T:").append(cypherMethods[choice])
							.append(";S:").append(ssid).append(";P:")
							.append(passwd).append("##IDENTITY##").append(name).append(";");
				}
				break;
			default:
				if (ssid.equals("") || passwd.equals("")) {
					Toast.makeText(this.getBaseContext(), "请填写完整信息",
							Toast.LENGTH_SHORT).show();
				} else {
					// 生成
					sb.append("WIFI:T:").append(cypherMethods[choice])
							.append(";P:").append(passwd).append(";S:")
							.append(ssid).append(";");
				}
				break;
		}

		// String text = ((TextView)
		// findViewById(R.id.textQR)).getText().toString();
		text = sb.toString();
		if (text != null && !text.equals("")) {
			Intent intent = new Intent(this, RashDisplayActivity.class);
			// ACTION 是 ENCODE
			intent.setAction(Intents.Encode.ACTION);
			// 类型是TEXT，这里可以有很多中类型，具体参见QRCodeEncoder源码
			intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
			// 数据，这里是字符串
			intent.putExtra(Intents.Encode.DATA, text);
			startActivity(intent);
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
			long arg3) {
		// 先简单处理
		this.choice = pos;
		if (pos == 0) {
			LinearLayout user_domain = (LinearLayout) findViewById(R.id.username_layout);
			user_domain.setVisibility(View.GONE);
			LinearLayout passwd_domain = (LinearLayout) findViewById(R.id.passwd_layout);
			passwd_domain.setVisibility(View.GONE);
		} else if (pos == 3) {
			LinearLayout user_domain = (LinearLayout) findViewById(R.id.username_layout);
			user_domain.setVisibility(View.VISIBLE);
			LinearLayout passwd_domain = (LinearLayout) findViewById(R.id.passwd_layout);
			passwd_domain.setVisibility(View.VISIBLE);

		} else {
			LinearLayout user_domain = (LinearLayout) findViewById(R.id.username_layout);
			user_domain.setVisibility(View.GONE);
			LinearLayout passwd_domain = (LinearLayout) findViewById(R.id.passwd_layout);
			passwd_domain.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// 什么都没选
		Toast.makeText(parent.getContext(), "什么都没做", Toast.LENGTH_SHORT).show();
	}
}
